import { useState, useContext } from 'react'
import { Input } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

import { DataContext } from '../../store/DataContext';

import './addFoodTag.scss'

export default function AddFoodTag() {

    const { data, dispatch } = useContext(DataContext)

    const [showAddInputVisible, setShowAddInputVisible] = useState(false)
    const [inputValue, setInputValue] = useState()

    const handleShowAddInput = () => {
        setShowAddInputVisible(true)
    }

    const handleAddFood = () => {
        let addItem = { id: data.length + 1, title: inputValue }
        dispatch({ type: 'set', value: [...data, addItem] })
        setShowAddInputVisible(false)
    }

    const handleInputChange = (e) => {
        setInputValue(e.target.value)
    }

    return (
        showAddInputVisible ?
            <Input
                className='turn_add_food_input'
                onPressEnter={handleAddFood}
                onChange={handleInputChange}
                autoFocus="autofocus"
                onBlur={handleAddFood}
            ></Input>
            :
            <div className='turn_add_food_tag' onClick={handleShowAddInput}>
                <PlusOutlined /> 添加
            </div>
    )
}
